import localforage from "localforage";
export default class GroupForage {
    constructor(modules) {
        this.modules = [...modules];
        localforage.config({
            driver: [localforage.INDEXEDDB, localforage.LOCALSTORAGE],
            name: "rambler-storage",
            description: "for rambler",
        });
    }

    /**
     * 取module模块的key
     * @param {*} module 模块名称
     * @param {*} key 键名称
     * @returns
     */
    getItem(module, key) {
        return new Promise((resolve, reject) => {
            if (!this.modules.includes(module)) {
                reject(`${module}不存在`);
            }
            const key = `${module}_${key}`;
            localforage.getItem(key).then(resolve).catch(reject);
        });
    }

    /**
     * 设置值
     * @param {*} module 模块名称
     * @param {*} key 键名
     * @param {*} value 支持的类型 Array, ArrayBuffer, Blob, Number, Object, String
     * @returns
     */
    setItem(module, key, value) {
        return new Promise((resolve, reject) => {
            if (!this.modules.includes(module)) {
                reject(`${module}不存在`);
            }
            const storageKey = `${module}_${key}`;
            localforage.setItem(storageKey, value).then(resolve).catch(reject);
        });
    }

    /**
     * 检测module模块是否存在key
     * @param {*} module 模块名称
     * @param {*} key 键
     */
    has(module, key) {
        return new Promise((resolve, reject) => {
            if (!this.modules.includes(module)) {
                reject();
            }
            const moduleKey = `${module}_${key}`;
            localforage
                .iterate((_, key) => {
                    if (key == moduleKey) {
                        return true;
                    }
                })
                .then((res) => (res ? resolve() : reject()))
                .catch(reject);
        });
    }
}
